# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase
from collections import defaultdict


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def groupStrings(self, words: List[str]) -> List[int]:
        def word_mask(w: str) -> int:
            x = 0
            for ch in w:
                x |= 1 << (ord(ch) - ord('a'))
            return x

        def find(x):
            if fa[x] == x:
                return x
            else:
                fa[x] = find(fa[x])
                return fa[x]

        def merge(i, j):
            nonlocal group_count, max_size
            if j not in fa:
                return
            x = find(i)
            y = find(j)

            if x == y:
                return

            fa[x] = y
            size[y] += size[x]
            max_size = max(max_size, size[y])
            group_count -= 1

        count_words = len(words)
        group_count = count_words
        max_size = 0
        fa = {}
        size = defaultdict(int)

        for word in words:
            mask = word_mask(word)
            fa[mask] = mask
            size[mask] += 1
            max_size = max(max_size, size[mask])
            if size[mask] > 1:
                group_count -= 1

        for x in fa:
            for i in range(26):
                merge(x, x ^ (1 << i))
                if (x >> i) & 1:
                    for j in range(26):
                        if ((x >> j) & 1) == 0:
                            merge(x, x ^(1 << i) | (1 << j))

        return [group_count, max_size]


if __name__ == '__main__':
    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        (["a","b","ab","cde"], [2, 3]),
        (["a","ab","abc"], [1, 3])
    ]

    for case_item in testcases:
        solution = Solution()
        # 获取测试用的case和期待的执行结果
        input1 = case_item[0]
        expect = case_item[len(case_item) - 1]
        exec_result = solution.groupStrings(input1)

        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

